/**
 * K3彩票部分js
 */
var running_time = 0;
//快3 和值玩法中的投注选项点击
var betting = new Array();
var oddsArr = new Array();

function init(resData){
	console.log(resData);
	$('.tag_lott_shangqi').html(resData.data.shangqi.period);
	// 当前期号的倒计时
	var now_timestamp  = (Date.parse(new Date()) / 1000) * 1; // js的时间戳会带毫秒
	// 页头开奖骰子
	clearTimeout(clear_kj_ready);
	shangqi_kj_reday(2000, resData.data.shangqi.code);
	if(!$.isEmptyObject(resData.data.lotting)){
		$('.tag_lott_lotting').html(resData.data.lotting.period);
		$('.tag_lott_next').html(resData.data.nextbet.period);
		// 当前期号结束时间减掉当前时间戳为剩下时间
		running_time = resData.data.lotting.stoptime - resData.data.suportData.nowTime;
		// 倒计时结束提示以及重新更新页面数据
		daojishi();
	}else{
		$('#id_k3_lottperiod').html('暂未开始');
		$('.tag_runningtime').html('--:--:--');
	}
}

/**
 * =========================================================================
 * 上期开奖结果，这里主要是js效果以及控制
 */
function shangqi_kaijiang(code_str){
	var baseClass     = 'tag_Award_Number Dice Dice';
	var award_numbers = $('.tag_Award_Number');
	var kaijiang_code = code_str.split(',');
	for(var i = 0; i < award_numbers.length; i++){
		award_numbers[i].className = baseClass + kaijiang_code[i];
	}
}

/**
 * 上期开奖前面旋转2秒后展示开奖结果
 * @param seconds
 */
var shangqi_kj = 0;
var clear_kj_ready = '';
function shangqi_kj_reday(seconds, code_str){
	if(seconds <= 0){
		shangqi_kaijiang(code_str);
		return;
	}
	if(shangqi_kj > 3){
		shangqi_kj = 0;
	}
	var baseClass     = 'tag_Award_Number Dice rDice';
	$('.tag_Award_Number').attr('class', baseClass + shangqi_kj);
	shangqi_kj++;
	if(code_str != 'null'){
		// 如果上期有开奖，则准备展示上期开奖结果
		seconds = seconds - 100;
	}
	clear_kj_ready = setTimeout('shangqi_kj_reday(' + seconds + ', "' + code_str + '")', 100);
}



/**
 * =========================================================================
 * 倒计时计算，返回00:00:00形式倒计时
 * @param second
 */
function daojishi (){
	var hour   = '00';
	var minute = '00';
	var second = '00';
	if (running_time <= 0){
		$('.tag_runningtime').html(hour + ':' + minute + ':' + second);
		// 当前期号结束，获取下批期号信息， 并重新载入数据.
		var content_msg  = resData.data.shangqi.period + '期已截止<br/>';
			content_msg += '当前期号<font style="color: red;">' + $('.tag_lott_next').html() + '</font><br/>';
			content_msg += '投注时请注意期号';
		layer_msg('温馨提示', content_msg, '');
		setTimeout("loadLotteryInfo()", 1000);
		return;
	}
	hour       = parseInt(running_time / (60 * 60));
	minute     = parseInt(running_time / (60));
	second     = parseInt(running_time % (60));
	if(hour == 0){
		hour = '00';
	}else if(hour > 0 && hour < 10){
		hour = '0' + hour;
	}
	if(minute == 0){
		minute = '00';
	}else if(minute > 0 && minute < 10){
		minute = '0' + minute;
	}
	if(second == 0){
		second = '00';
	}else if (second > 0 && second < 10){
		second = '0' + second;
	}
	$('.tag_runningtime').html(hour + ':' + minute + ':' + second);
	running_time--;
	setTimeout("daojishi()", 1000);
}

/**
 *  =============================================================
 *  切换玩法的控制与显示方法
 *  @param play  : 玩法
 */
var choice_k3_play = '';
function k3_play_controller(play){
	if (!play) play = 'item_he';
	var re_play     = play.toUpperCase();
	re_play         = re_play.replace('ITEM_', '');
	var nowPlay     = resData.data.codeKeyList['TSK3-']['K3|'];
	// 清除当前选择
	clear_betting();
	choice_k3_play  = play;
	// 后缀key值补偿
	var spk = '';
	switch(re_play){
		case 'HE':
			var playItem   = resData.data.playItem.HE;
			var item_sthtx = '<div data-v-31934d5a="" class="Method Method0">';
				item_sthtx += '		<p data-v-31934d5a="" class="MethodMsg">' + playItem.play_explain + '</p> '; 
				item_sthtx += '		<ul data-v-31934d5a="" class="tag_play_X">';
				
				$.each(playItem.item, function (index, value){
					item_sthtx += ' 	<li data-v-31934d5a="" class="">';
					item_sthtx += value.title;
					if(value.title == '大'){
						spk = 'DA';
					}else if(value.title == '小'){
						spk = 'XIAO';
					}else if(value.title == '单'){
						spk = 'DAN';
					}else if(value.title == '双'){
						spk = 'SHUANG';
					}else{
						spk = value.title;
					}
					item_sthtx += ' 	<p data-v-31934d5a="">赔率' + nowPlay['HZ' + spk].odds + '<font style="display: none;">' + nowPlay['HZ' + spk].odds + '</font></p>';
					item_sthtx += ' 	</li>';
				});
				item_sthtx += '		</ul>'; 
				item_sthtx += '</div>';
			$('.MethodWrap').html(item_sthtx);
			break;
		case 'STHTX':
			var playItem   = resData.data.playItem.STHTX;
			break;
		case 'STHDX':
			var playItem   = resData.data.playItem.STHDX;
			break;
		case 'SBTH':
			var playItem   = resData.data.playItem.SBTH;
			break;
		case 'SLHTX':
			var playItem   = resData.data.playItem.SLHTX;
			break;
		case 'ETHFX':
			var playItem   = resData.data.playItem.ETHFX;
			break;
		case 'ETHDX':
			var playItem   = resData.data.playItem.ETHDX;
			break;
		case 'EBTH':
			var playItem   = resData.data.playItem.EBTH;
			break;
	}
	if(re_play != 'HE'){
		// 只有和值的展现效果不一样
		var item_ebth = '<div data-v-31934d5a="" class="Method Method' + playItem.number + '">';
			item_ebth += '	<p data-v-31934d5a="" class="MethodMsg">' + nowPlay[re_play].explain + '</p>'; 
			item_ebth += '		<ul data-v-31934d5a="" class="tag_play_X">'; 
			$.each(playItem.item, function (index, value){
				item_ebth += '		<li data-v-31934d5a="" class="" id="' + index + '">';
				item_ebth += value.title;
				item_ebth += '<p style="display: none;">' + value.odds + '</p>';
				item_ebth += '		</li>';
			});
			item_ebth += '		</ul>'; 
			item_ebth += '</div>';
		$('.MethodWrap').html(item_ebth);
	}
	if(!$.isEmptyObject(nowPlay[re_play])){
		$('.tag_pc_bonus').html(nowPlay[re_play].odds);
	}
	
	$('.tag_bet_play_title').html(playItem.title);
}

function clear_betting(){
	if(betting){
		// 清空预投注
		betting.length = 0;
		// 清空最大赔率
		oddsArr.length = 0;
	}
	
	// 清空choice框
	$('.tag_play_he li').removeClass('checked');
	$('.tag_play_X li').removeClass('checked');
	$('.tag_betting_content').hide();
	$('.tag_betting_count').html('');
	$('.tag_betting_pay_everyone').val('');
	$('.tag_betting_tips_maxodds').hide();
	$('.tag_betting_tips').show();
}

function check_bet_type(type){
	var res = '';
	switch(type){
		case 'item_ethdx':
			res = check_bet_ethdx();
			break;
		case 'item_ebth':
			res = check_bet_ebth();
			break;
		case 'item_sbth':
			res = check_bet_sbth();
			break;
	}
	return res;
}

function check_bet_sbth(){
	var count = 0;
	for(var i = 0; i < betting.length - 2; i++){
		for(var j = i + 1; j < betting.length; j++){
			for(var z = j + 1; z < betting.length; z++){
				count++;
			}
		}
	}
	res = {'bettint_number': count};
	return res;
}

/**
 * 计算二不同号的预投注数目
 */
function check_bet_ebth(){
	var count = 0;
	for(var i = 0; i < betting.length - 1; i++){
		for(var j = i + 1; j < betting.length; j++){
			count++;
		}
	}
	res = {'bettint_number': count};
	return res;
}

/**
 * 二同号单选的方式有点不一样的情况，比如选点亮了22选项，那再点击2选项时，22要失效。同数号仅存一个
 * 至于赔率不用考虑，单种玩法赔率一致（和值玩法除开）。
 * @return dom_id，返回的dom_id的预投注状态取消
 */
function check_bet_ethdx(){
	// 检查当前选项中的预投注号是否有同号
	var dom_id        = '';
	var repeat        = -1;
	var res           = '';
	if(choice_k3_play == 'item_ethdx' && betting.length > 0){
		var bet_pop   = betting.pop();
		var check_bet = bet_pop.substr(0,1);
		$.each(betting, function (index, value){
			if(value.indexOf(check_bet) >= 0){
				// 找到重复值， 准备删除前一个预投注选项
				dom_id  = 'item_' + value;
				repeat  = index;
			}
		});
		betting.push(bet_pop);
		if(repeat > -1){
			betting.splice(repeat, 1);
		}
		
		// 统计二同号单选预投注份数
		var double_count = 0;
		var single_count = 0;
		$.each(betting, function (index, value){
			if(value.length == 2){
				double_count++;
			}else{
				single_count++;
			}
		})
		res = {'dom_id':dom_id, 'bettint_number': double_count * single_count};
	}
	return res;
}

// 倒计时结束提示弹框
function layer_msg(title, msg, type){
	if(!title){return}
	switch(type){
		case 'submit':
			var bet_status = false;
			var resMsg     = '';
			layer.open({
				title: title,
				content: msg,
				className: 'layui-m-tag-msg',
				btn: ['投注','取消'],
				yes: function (index){
					// 提交投注请求
					var param  = 'lottery=k3';
						param += '&play=' + choice_k3_play;
						param += '&betting=' + betting;
						param += '&no=' + resData.data.lotting.id;
						param += '&eo_money=' + $('.tag_betting_pay_everyone').val();
						param += '&lott_id=' + $('#choice_play_id').val();
					$.ajax({  
		        		type:'post',    
		        	    url:betUrl,  
		        	    data:param,  
		        	    cache:false,  
		        	    dataType:'json',  
		        	    async:false,
		        	    success:function(res){  
		        	    	if(res.status == 'success'){
		        	    		bet_status = true;
		            	    }
		        	    	resMsg = res.msg;
		        	    }  
		        	})
		        	layer.close(index);
		        	if(bet_status){
						layer_msg('温馨提示', '<span style="color:red">投注成功</span>，您可以在我的账户查看注单详情', 'success');
			    		clear_betting();
					}else{
						layer_msg('温馨提示', resMsg, '');
					}
				}
			});
			break;
		case 'success':
			layer.open({
	            title: '温馨提示',
	            content: '<span style="color:red">投注成功</span>，您可以在我的账户查看注单详情',
	            className: 'layui-m-tag-msg',
	            btn: ['继续投注', '查看注单'],
	            yes: function (index){
					// 继续投注
	            	layer.close(index);
	            },
	            no: function (index){
	            	// 查看注单
	            	window.location = memberBet;
	            }
	        });
			break;
		default:
			layer.open({
				title: title,
				content: msg,
				className: 'layui-m-tag-msg',
				btn: ['确定'],
				yes: function (index){
					layer.close(index);
				}
			});
			break;
	}
}

/**
 * 获取上一期的开奖情况
 */
function getLastPerOpen(){
	var lastPerRequest = {'operation':'getPerInfo', 'pid':resData.data.shangqi.id};
	$.ajax({  
		type:'post',    
	    url: getLastData,  
	    data:'data=' + JSON.stringify(lastPerRequest),  
	    cache:false,  
	    dataType:'json',  
	    success:function(res){  
	    	if(res.perInfo.code){
	    		// 清除settimeout
	    		clearTimeout(clear_kj_ready);
	    		// 调用上期开奖
	    		shangqi_kaijiang(res.perInfo.code);
	    	}
	    }
	})
	setTimeout("getLastPerOpen()", 1000*60);
}

// 页面完成后最后执行
window.onload = function (){
	k3_play_controller('');
}
